#include "esp_camera.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include "Config.h"
#include "camera_pins.h"
#include "camera_wrap.h"

#ifdef WORKMODE1

#include <WebSocketsServer.h>

#endif

uint8_t *jpgBuff = new uint8_t[68123];
size_t jpgLength = 0;
uint8_t camNo = 0;
bool clientConnected[3] = {false, false, false};

int8_t appMode = -1;
TaskHandle_t uploadImageTaskHand = nullptr;

#ifdef WORKMODE1
WebSocketsServer webSocket = WebSocketsServer(86);
void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length);
void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length)
{
    
    switch (type)
    {
        case WStype_DISCONNECTED:
            Serial.printf("[%u] Disconnected!\n", num);
            if (num < 3)
            {
                camNo = num;
                clientConnected[num] = false;
                String command = "/MOVE:0,0";
                Serial.print(command);
            }
            break;
        case WStype_CONNECTED:
            if (num < 3)
            {
                clientConnected[num] = true;
            }
            break;
        case WStype_TEXT:
        case WStype_BIN:
        case WStype_ERROR:
        case WStype_FRAGMENT_TEXT_START:
        case WStype_FRAGMENT_BIN_START:
        case WStype_FRAGMENT:
        case WStype_FRAGMENT_FIN:
            break;
    }
}
#endif

#ifndef WORKMODE1

void uploadImageTask(void *)
{
    Serial.println(appMode);
    HTTPClient http;
    unsigned long timestamp = millis();
    http.begin(String(http_url) + "?mode=" + String(appMode));
    http.addHeader("Content-type", "text/plain");
    int httpCode = http.POST((String) appMode);
    if (httpCode == HTTP_CODE_OK)
    {
        Serial.println("image post success");
        Serial.print("image post time: ");
        Serial.print(millis() - timestamp);
        Serial.println(" ms");
    } else
    {
        Serial.println("text post err");
    }
    http.end();
//    HTTPClient http;
    unsigned long timestamp1 = millis();
    camera_fb_t *fb = esp_camera_fb_get();
    http.begin(String(http_url) + "?mode=" + String(appMode));
    http.addHeader("Content-type", "image/jpeg");
    int httpCode1 = http.POST(fb->buf, fb->len);
    if (httpCode1 == HTTP_CODE_OK)
    {
        Serial.println("image post success");
        Serial.print("image post time: ");
        Serial.print(millis() - timestamp1);
        Serial.println(" ms");
    } else
    {
        Serial.println("image post err");
    }
    http.end();
    esp_camera_fb_return(fb);
    uploadImageTaskHand = nullptr;
    vTaskDelete(NULL);
}

#endif

void scanBtn(void *pv)
{
    while (1)
    {
        uint32_t key_val = analogRead(ADC_BTN);
        uint32_t key_val1 = analogRead(ADC_PRESSURE);
        Serial.println(key_val1);
        if (key_val > 300 && key_val < 600)
        {//400-500
            appMode = 1;
        } else if (key_val > 1300 && key_val < 1600)
        {//1400-1500
            appMode = 2;
        } else if (key_val > 2900 && key_val < 3200)
        {//3000-3100
            appMode = 3;
        } else if (key_val > 2300 && key_val < 2600)
        {//2400-2500
            appMode = 4;
        }
        
        if (key_val1 < 500)
        {
            if (appMode != -1)
            {
                if (uploadImageTaskHand == nullptr)
                {
                    xTaskCreate(uploadImageTask, "uploadImageTask", 1024 * 5, nullptr, 1, &uploadImageTaskHand);
                } else
                {
                    Serial.println("重复创建任务!!!");
                }
            } else
            {
                Serial.println("请先选择模式!!!");
            }
            
        }
        vTaskDelay(300);
    }
}

void setup()
{
    Serial.begin(115200);
    pinMode(13, OUTPUT);
    digitalWrite(13, HIGH);
    delay(100);
    initCamera();
    
    grabImage(jpgLength, jpgBuff);
    WiFi.begin(ssid, password);
//    WiFi.setSleep(true);
    
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    
    Serial.println("");
    Serial.println("WiFi connected");
    
    Serial.print("Camera Ready! Use 'http://");
    Serial.print(WiFi.localIP());
    Serial.println("' to connect");
#ifdef WORKMODE1
    webSocket.begin();
    webSocket.onEvent(webSocketEvent);
#endif
    xTaskCreate(scanBtn, "scanBtn", 1024 * 5, nullptr, 1, nullptr);
}

//uint32_t iii = 0;xzx

void loop()
{
#ifdef WORKMODE1
    //    Serial.println(webSocket.sendTXT(camNo,sendWebData););
        webSocket.loop();
        if (clientConnected[camNo] == true)
        {
            grabImage(jpgLength, jpgBuff);
            webSocket.sendTXT(camNo, ((String) appMode).c_str());
            webSocket.sendBIN(camNo, jpgBuff, jpgLength);
    //        Serial.println(++iii);
            delay(10);
        } else
        {
            delay(100);
        }

#endif
}
